import React, { useState, useEffect } from "react";
import { NavBar } from "react-vant"; //导航栏
import { useNavigate } from "react-router-dom";
import { Search,Toast } from "react-vant"; //搜索
import "./scss/Classfy.scss";
import axios from "./untils/Axios";
import { InfiniteScroll } from "antd-mobile";
import { sleep } from "antd-mobile/es/utils/sleep";
import { useLocation } from "react-router-dom";
import { ShoppingCartO   } from '@react-vant/icons';
export default function Classfy() {
  const location = useLocation();
  //获取数据
  let nav = useNavigate();
  const [value, setValue] = useState(""); //搜索
  const backgroundStyle = {
    background: "linear-gradient(to bottom, #B9C9E5, #FFFFFF)",
  };
  const [oneData, setOneData] = useState([]); //一级分类数据
  const [twoData, settwoData] = useState([]); //渲染标题
  const [bookData, setBookData] = useState([]); //渲染数据
  const [oldbook, setOldbook] = useState([]); //渲染数据
  const [typeOneId, setTypeOneId] = useState(location.state._id); //一级分类id
  const [typeTwoId, setTypeTwoId] = useState(""); //二级分类id
  const [hasMore, setHasMore] = useState(true); //是否还有更多数据
  const [page, setPage] = useState(1); //当前页数
  const [pageSize, setPageSize] = useState(7); //每页条数

  let getdata = async () => {
    let { data } = await axios.get("/jjt/getdatajjt");
    console.log(data, 999);
    setOneData(data.oneData);
    settwoData(data.twoData);
    console.log(data.oneData, 1);
    console.log(data.twoData, 2);
  };
  //无限加载

  async function loadMore() {
    const append = await axios
      .get("/jjt/getdatajjt", {
        params: { page, pageSize, typeOneId, typeTwoId, value },
      })
      .then(async (res) => {
        await sleep(30);
        // console.log(res.data.bookData, 888);
        return res.data.bookData;
      });
    setPage(page + 1);
    setBookData((val) => [...val, ...append]);
    setOldbook((val) => [...val, ...append])
    // console.log(bookData);
    setHasMore(append.length > 0);
  }
  //搜索
  let tosearch = () => {
    console.log(value);
    let copy = [...oldbook]
    copy = copy.filter(item => item.name.includes(value))
    console.log(copy,12121)
    setBookData(copy)
    setTypeTwoId("")
  }
    //加入购物车
    let tocar = async(item) => {
      console.log(item,555555555)
      let {data} =  await axios.post("/jjt/caradd", item);
      console.log(data,6666)
      if(data.code===200){
        Toast({
          message: '加入购物车成功',
          // icon: <FireO />,
        })
      }else{
        Toast({
          message: '加入购物车失败',
        })
      }
    }
  //接受分类路由参数
  useEffect(() => {
    getdata();
  }, [typeTwoId,typeOneId]);
  return (
    <div className="classfy">
      <div className="classfy1">
        <NavBar
          title="全部分类"
          leftText="返回"
          //   rightText="按钮"
          onClickLeft={() => nav("/jjthome")}
          onClickRight={() => console.log("按钮")}
        />
      </div>

      <div className="classfy2" style={backgroundStyle}>
        <Search
          showAction
          background="rgba(255, 255, 255, 0)"
          actionText={
            <div
              onClick={() => {
               tosearch()
              }}
            >
              搜索
            </div>
          }
          value={value}
          onChange={setValue}
          placeholder="请输入搜索关键词"
        />

        <div className="classfy2con">
          <div className="classfyleft">
            <li
              onClick={() => {
                if(hasMore===false){
                setTypeOneId("");
                setTypeTwoId("")
                setBookData([]);
                setOldbook([])
                setPage(1);
                setHasMore(true);
                }
                
              }}
              className={typeOneId == "" ? "actli" : ""}
            >
              全部
            </li>
            {oneData.map((item) => (
              <li
                className={item._id == typeOneId ? "actli" : ""}
                key={item._id}
                onClick={() => {
                    if(hasMore==false){
                        setTypeOneId(item._id);
                        setTypeTwoId("")
                        setBookData([]);
                        setOldbook([])
                        setPage(1);
                        setHasMore(true);
                    }
                }}
              >
                {item.name}
              </li>
            ))}
          </div>
          <div className="classright">
            {typeOneId !== "" ? (
              <div className="classrightcon">
                <button
                  className="btn2"
                  onClick={() => {
                    setTypeTwoId("");
                    setOldbook([])
                    setBookData([]);
                    setPage(1);
                    setHasMore(true);
                  }}
                  style={
                    typeTwoId == ""
                      ? {
                          background: "#E5ECFF",
                          border: " 1px solid #5D7AD5",
                        }
                      : {}
                  }
                >
                  {" "}
                  全部
                </button>
                {twoData
                  .filter((item) => item.typeOneId._id == typeOneId)
                  .map((item) => (
                    <button
                      className={item.name.length >= 3 ? "btn1" : "btn2"}
                      style={
                        typeTwoId == item._id
                          ? {
                              background: "#E5ECFF",
                              border: " 1px solid #5D7AD5",
                            }
                          : {}
                      }
                      key={item._id}
                      onClick={() => {
                        setTypeTwoId(item._id);
                        let copy = oldbook.filter(ele=>JSON.stringify(ele.typeTwoId._id)==JSON.stringify(item._id));
                        setBookData(copy);
                      }}
                    >
                      {item.name}
                    </button>
                  ))}
              </div>
            ) : (
              ""
            )}
            <div>
              {bookData.map((item) => (
                <div key={item._id} className="classfycon3" >
                  <div className="classfycon3left" onClick={()=>{nav(`/detail?id=${item._id}`)}}>
                    <img src={item.image} alt=""></img>
                  </div>
                  <div className="classfycon3right">
                    <div style={{ fontSize: "14px", fontWeight: "bold" }}>
                      {item.name}
                    </div>
                    <div>
                      <span className="span1">￥{item.price}</span>
                      <span className="span2">
                      <ShoppingCartO onClick={()=>{tocar(item)}}  />
                      </span>
                    </div>
                  </div>
                </div>
              ))}
              <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
